package org.jix.framework.biz.context.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jix.framework.biz.context.holder.LoginUserContextHolder;
import org.jix.framework.common.constant.GlobalConstants;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author stark
 * @date 2025/6/3 11:38
 * @description
 **/
@Slf4j
public class HeaderUserID2ContextFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        //从请求头中获取用户ID
        String userID = request.getHeader(GlobalConstants.USER_ID);

        log.info("## HeaderUserId2ContextFilter, 用户 ID: {}", userID);

        //判断请求头中是否存在UserID
        if (StringUtils.isBlank(userID)) {
            //为空直接放行
            filterChain.doFilter(request, response);
            return;
        }
        //请求头中存在UserID，设置到threadLocal中
        log.info("===== 设置 userId 到 ThreadLocal 中， 用户 ID: {}",userID);
        LoginUserContextHolder.setUserID(userID);

        try {
            //将请求和响应传递给下一个过滤器
            filterChain.doFilter(request, response);
        } finally {
            //删除threadLocal，防止内存泄露
            LoginUserContextHolder.remove();
            log.info("===== 删除 ThreadLocal， userId: {}", userID);
        }

    }
}
